package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.team;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserWallet;
import com.gzhryc.shared_device.oem.code.user.dao.db.UserWalletOperate;
import com.gzhryc.shared_device.oem.code.user.dao.enums.UserTransferMoneyOrderEnum;
import com.gzhryc.shared_device.oem.code.user.services.UserTransferMoneyOrderService;
import com.gzhryc.shared_device.oem.code.user.services.UserWalletOperateService;
import com.gzhryc.shared_device.oem.code.user.services.UserWalletService;
import com.gzhryc.shared_device.oem.code.user.services.dto.UserWalletOperateSearch;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserWalletController {

    @Route(value = {"/team/user/wallet/info.html"})
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request, "id");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(id != null && loginUser != null) {
            //获取代理的钱包，整理出账号组
            List<Long> accountGroupIds = new ArrayList<>();
            List<UserWallet> loginUserWalletList = UserWalletService.self().findJoinByUserId(loginUser.getId());
            if(loginUserWalletList != null && loginUserWalletList.size() > 0){
                for(UserWallet wallet : loginUserWalletList){
                    accountGroupIds.add(wallet.getAccountGroupId());
                }
            }

            AgentRelation agentRelation = AgentRelationService.self().getJoinByKeys(loginUser.getId(),id);
            if (agentRelation != null) {
                WebUtils.setAttribute(request, agentRelation.getRelationUser());
                if(accountGroupIds.size() > 0) {
                    List<UserWallet> walletList = UserWalletService.self().findJoinByUserId(agentRelation.getRelationUserId());
                    if (walletList != null && walletList.size() > 0) {
                        List<UserWallet> temp = new ArrayList<>();
                        for(UserWallet wallet : walletList){
                            if(accountGroupIds.contains(wallet.getAccountGroupId())){
                                temp.add(wallet);
                            }
                        }
                        request.setAttribute("walletList", temp);
                    }
                }

                Integer transferMoney = UserTransferMoneyOrderService.self()
                        .sumTransferMoneyByUserIdAndState(agentRelation.getRelationUserId(), UserTransferMoneyOrderEnum.State.Success.index());
                request.setAttribute("transferMoneyStr", NumberTools.getMoneyStr(transferMoney));
            }
        }
        return "/team/user/wallet/info.html";
    }

    @Route(value = {"/team/user/wallet/withdrawal_money/transfer.html"})
    public String transfer(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request, "userId");
        Long accountGroupId = WebUtils.getLong(request, "accountGroupId");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(userId != null && loginUser != null) {
            AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),userId);
            if(agentRelation != null) {
                UserWallet wallet = UserWalletService.self().getByKeys(userId,accountGroupId);
                WebUtils.setAttribute(request, wallet);
            }
        }
        return "/team/user/wallet/transfer.html";
    }

    @Route(value = {"/team/user/wallet/withdrawal_money/transfer.do"})
    public AjaxResult doTransfer(HttpServletRequest request, HttpSession session){
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"转出失败");
        Long userId = WebUtils.getLong(request, "userId");
        Long accountGroupId = WebUtils.getLong(request, "accountGroupId");
        Double money = WebUtils.getDouble(request,"money");
        String operateNote = WebUtils.getString(request,"operateNote");

        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(userId != null && loginUser != null) {
            AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),userId);
            if(agentRelation != null) {
                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
                operateInfo.setOperateNote(operateNote);

                try {
                    if (UserWalletService.self().transferMoneyToWithdrawal(userId,accountGroupId,NumberTools.changeMoneyLi(money), operateInfo)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }else{
                result.setCode(DtoConstants.NOT_POWER,"无权限查操作");
            }
        }
        return result;
    }

    @Route(value = {"/team/user/wallet/operate/list.html"})
    public String operateList(HttpServletRequest request) {
        Long userId = WebUtils.getLong(request, "userId");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if(userId != null && loginUser != null) {
            AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(), userId);
            if (agentRelation != null) {
                Long accountGroupId = WebUtils.getLong(request, "accountGroupId");
                UserWallet wallet = UserWalletService.self().getJoinByKeys(userId, accountGroupId);
                WebUtils.setAttribute(request, wallet);
            }
        }
        return "/team/user/wallet/operate_record.html";
    }

    @Route(value = "/team/user/wallet/operate/list.data")
    public ListResult<UserWalletOperate> operateListData(HttpServletRequest request) {
        ListResult<UserWalletOperate> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        UserWalletOperateSearch search = WebUtils.getParameter(request,UserWalletOperateSearch.class);
        if(search.getUserId() != null) {
            Integer pageNo = WebUtils.getInteger(request, "page", 1);
            Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if(search.getUserId() != null && loginUser != null) {
                AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(), search.getUserId());
                if (agentRelation != null) {
                    result.getBody().setData(UserWalletOperateService.self(new Date()).findBySearch(search, pageNo, pageLimit));
                    if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }else{
                    result.setCode(DtoConstants.NOT_POWER,"无权限查看");
                }
            }
        }
        return result;
    }
}
